//
//  BHCompetitionApplyViewController.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/6/16.
//

import UIKit

class BHCompetitionApplyViewController: BHBaseViewController {
    
    var refreshDetailBlock:(() -> Void)?
    
    
    lazy var tableView: UITableView = {
        let view = UITableView.buildTableView(style: .grouped)
        view.frame = CGRect(x: 0, y: UIScreen.begainY, width: UIScreen.width, height: UIScreen.showHeight-BHCompetitionApplyBottomView.viewHeight)
        view.delegate = self
        view.dataSource = self
        return view
    }()
    
    lazy var bottomView: BHCompetitionApplyBottomView = {
        let view = BHCompetitionApplyBottomView.loadFromXib()
        view.frame = CGRect(x: 0, y: UIScreen.height-BHCompetitionApplyBottomView.viewHeight, width: UIScreen.width, height: BHCompetitionApplyBottomView.viewHeight)
        view.delegate = self
        return view
    }()
    lazy var userWritView: BHApplyUserInfoWriteView = {
        let view = BHApplyUserInfoWriteView.init(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.height))
        view.delegate = self
        return view
    }()
    lazy var payBottomView: BHApplyPayBottomSheetView = {
        let view = BHApplyPayBottomSheetView.init(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.height))
        view.delegate = self
        return view
    }()
    
    /**报名类型 0个人赛 1组队赛*/
    var applyType: Int = 0
    var gameId: String = ""
    
    var price: String = "" {
        didSet {
            if price.isEmpty == true {
                self.payBottomView.price = "0.00"
                self.bottomView.price_label.text = "0.00"
            }else {
                self.payBottomView.price = price
                self.bottomView.price_label.text = price
            }
        }
    }
    fileprivate var enrollJsonDic: [String:Any] = [:]
    fileprivate var groupItemArray: [BHCompetitionApplyGroupItemModel]  = []
    fileprivate var choseGroupModel: BHCompetitionApplyGroupItemModel = BHCompetitionApplyGroupItemModel.init()
    fileprivate var personlaModel: BHApplyUserModel = BHApplyUserModel.init() // 个人赛
    fileprivate var teamUserArray: [BHApplyUserModel] = [] // 团队报名成员
    fileprivate var teamNameText: String = ""
    
    fileprivate var businessId: String = ""
    fileprivate var orderText: String = ""
    override func viewDidLoad() {
        super.viewDidLoad()
        self.bh_navigationBar.title_label.text = "赛事报名"
        self.regisetCell()
        
        self.view.addSubview(self.tableView)
        self.view.addSubview(self.bottomView)
        self.view.addSubview(self.userWritView)
        self.view.addSubview(self.payBottomView)
        
        self.queryGroupService()
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        self.view.bringSubviewToFront(self.userWritView)
        self.view.bringSubviewToFront(self.payBottomView)
    }
    
    
}

extension BHCompetitionApplyViewController: BHApplyPayBottomSheetViewDelegate {
    func goPayAct() {
        self.goAlipayAct()
    }
}

extension BHCompetitionApplyViewController: BHApplyUserInfoWriteViewDelegate {
    func applyWriteUserInfoCall(model: BHApplyUserModel, index: Int) {
        if self.applyType == 0 {
            self.personlaModel = model
        }else { // 团体赛
           
        }
        self.tableView.reloadData()
    }
}

extension BHCompetitionApplyViewController {
    func regisetCell()  {
        self.tableView.register(UINib.init(nibName: "BHCompetitionApplyGroupCell", bundle: nil), forCellReuseIdentifier: "BHCompetitionApplyGroupCell")
        self.tableView.register(BHApplyGroupLimitCell.self, forCellReuseIdentifier: "BHApplyGroupLimitCell")
        self.tableView.register(UINib.init(nibName: "BHApplyUserAddCell", bundle: nil), forCellReuseIdentifier: "BHApplyUserAddCell")
        self.tableView.register(UINib.init(nibName: "BHApplyGroupUserAddCell", bundle: nil), forCellReuseIdentifier: "BHApplyGroupUserAddCell")
        self.tableView.register(UINib.init(nibName: "BHApplyTeamTextFieldCell", bundle: nil), forCellReuseIdentifier: "BHApplyTeamTextFieldCell")
    }
}
extension BHCompetitionApplyViewController: BHCompetitionApplyBottomViewDelegate {
    func applyBottomDidSelectIndex(index: Int) {
        self.checkAvalidInfo()
    }
}

extension BHCompetitionApplyViewController {
    func checkAvalidInfo()  {
        if self.choseGroupModel.groupId.isEmpty == true {
            BHToast.toast(text: "请选择分组")
            return
        }
        
        if self.choseGroupModel.leftNumber <= 0 {
            BHToast.toast(text: "当前分组名额不足，请更换组别或联系管理员")
            return
        }
        if self.applyType == 1 {
            if self.teamNameText.isEmpty == true {
                BHToast.toast(text: "请填写战队名称")
                return
            }
            if self.teamUserArray.count > self.choseGroupModel.limitPerson {
                BHToast.toast(text: "当前团队赛队伍最多只能添加\(self.choseGroupModel.limitPerson)人")
                return
            }
            for model in self.teamUserArray {
                for (_,content) in model.textDic {
                    let val = content as! String
                    if val.isEmpty == true {
                    BHToast.toast(text: "请填写完整个人报名信息")
                    return
                    }
                }
            }
        }else {
            for (_,content) in self.personlaModel.textDic {
                let val = content as! String
                if val.isEmpty == true {
                BHToast.toast(text: "请填写完整个人报名信息")
                return
                }
            }
        }
        
        self.applyInfoService()
        
    }
}


extension BHCompetitionApplyViewController: UITableViewDataSource {
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        self.view.endEditing(true)
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            let row = self.groupItemArray.count/4
            let last = self.groupItemArray.count%4
            if last != 0 {
                return row+1
            }else {
                return row
            }
        }else if section == 1{
            return 1
        }else {
            if self.applyType == 0 {
                return 1
            }else {
                return 1+self.teamUserArray.count
            }
        }
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return 46
            
        }else if indexPath.section == 1 {
            return 56
            
        }else {
            if self.applyType == 0 {
                return 80
            }else {
                if indexPath.row == 0 {
                    return 60
                }else {
                    return 80
                }
            }
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 1 {
            return 0.0001
        }
        return 44
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.001
    }
    
}

extension BHCompetitionApplyViewController: UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 1 {
            return nil
        }
        let view = UIView.init(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 44))
        var label = view.viewWithTag(200) as? UILabel
        if label == nil {
            label = UILabel.init(frame: CGRect(x: 17, y: 10, width: UIScreen.width-40, height: 34))
            label?.textColor = .color_222222
            label?.font = .systemFont(ofSize: 14, weight: .medium)
            label?.tag = 200
            view.addSubview(label!)
        }
        if section == 0 {
            label?.text = "选择组别"
        }else {
            label?.text = "参赛者信息"
        }
        return view
        
    }
 
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "BHCompetitionApplyGroupCell", for: indexPath) as! BHCompetitionApplyGroupCell
            cell.configItem(array: self.groupItemArray, index: indexPath.row)
            cell.choseGroupActBlock = {[weak self] model in
                if model.leftNumber > self?.teamUserArray.count ?? 0 { // 名额不够
                    BHToast.toast(text: "您选择的分组剩余人员名额少于您报名人数，请删减人数")
                    return
                }
                
                if model.groupId != self?.choseGroupModel.groupId ?? "" {
                    self?.choseGroupModel.chose = false
                }
                self?.choseGroupModel = model
                
                tableView.reloadData()
            }
            return cell
        }else if indexPath.section == 1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "BHApplyGroupLimitCell", for: indexPath) as! BHApplyGroupLimitCell
            if self.choseGroupModel.groupId.isEmpty == false {
                if self.applyType == 1 {
                    cell.limit_label.text = "\(self.choseGroupModel.name)限额\(self.choseGroupModel.totalNumber)人，目前还剩\(self.choseGroupModel.leftNumber)人"
                }else {
                    cell.limit_label.text = "\(self.choseGroupModel.name)限额\(self.choseGroupModel.limitTeam)人，目前还剩\(self.choseGroupModel.leftNumber)人"
                }
            }else {
                cell.limit_label.text = "当前无可报名的分组，请联系管理员"
            }
            return cell
        }else {
            if self.applyType == 0 {
                let cell = tableView.dequeueReusableCell(withIdentifier: "BHApplyUserAddCell", for: indexPath) as! BHApplyUserAddCell
                cell.model = self.personlaModel
                return cell
            }else {
                if indexPath.row == 0 {
                    let cell = tableView.dequeueReusableCell(withIdentifier: "BHApplyTeamTextFieldCell", for: indexPath) as! BHApplyTeamTextFieldCell
                    cell.teamNameTextField.text = self.teamNameText
                    cell.teamNameDidEndEditingBlock = { [weak self] teamName in
                        self?.teamNameText = teamName
                    }
                    return cell
                }else {
                    let cell = tableView.dequeueReusableCell(withIdentifier: "BHApplyGroupUserAddCell", for: indexPath) as! BHApplyGroupUserAddCell
                    cell.operationBtn.isSelected = indexPath.row != 1
                    let model = self.teamUserArray[indexPath.row-1]
                    cell.model = model
                    cell.operationBtn.addBtnAction(action: { [weak self] (_) in
                        if indexPath.row == 1 { // +
                            if self?.choseGroupModel.leftNumber ?? 1 > self?.teamUserArray.count ?? 0{
                                BHToast.toast(text: "当前分组剩余人员名额不足")
                                return
                            }
                            let model = BHApplyUserModel.init()
                            model.textDic = self?.enrollJsonDic ?? [:]
                            self?.teamUserArray.append(model)
                        }else {  // -
                            self?.teamUserArray.remove(at: indexPath.row-1)
                        }
                        tableView.reloadData()
                        tableView.scrollToRow(at: IndexPath.init(row: self?.teamUserArray.count ?? 0, section: 2), at: .bottom, animated: true)
                    }, for: .touchUpInside)
                    return cell
                }
            }
            
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        self.view.endEditing(true)
        if indexPath.section == 2 {
            if self.applyType == 0 { // 个人赛
                self.userWritView.writeModelAndIndex(model: self.personlaModel, index: 0)
                self.userWritView.show()
            }else {
                if indexPath.row != 0 {
                    let model = self.teamUserArray[indexPath.row-1]
                    self.userWritView.writeModelAndIndex(model: model, index: indexPath.row-1)
                    self.userWritView.show()
                }
            }
        }
    }
}

extension BHCompetitionApplyViewController {
    func applyInfoService()  {
        
        SVProgressHUD.show()
        let dic = self.appendDic()
        
        let manager = BHHTTPClient.init()
        manager.post(url: String.game_detail_applyAct_url, paramters: dic) { (success, errorMsg, responseDic) in
            
            if success == true {
                self.refreshDetailBlock?()
                if self.price.isEmpty == true || self.price == "0" || self.price == "0.0" || self.price == "0.00"{ // 免费赛事
                    SVProgressHUD.dismiss()
                    BHToast.toast(text: "报名成功")
                    DispatchQueue.main.asyncAfter(deadline: DispatchTime.init(uptimeNanoseconds: 1)) {
                        self.navigationController?.popViewController(animated: true)
                    }
                }else {
                    self.businessId = BHJsonTool.decodeStringFromDic(dic: responseDic, key: "result")

                    self.createOrderService()
                }
            }else {
                SVProgressHUD.dismiss()
                BHToast.toast(text: errorMsg) 
            }
        }
        
    }
    
    func appendDic() -> [String:Any] {
        var dic: [String:Any] = [:]
        dic["eventId"] = self.gameId
        dic["teamId"] = self.choseGroupModel.groupId
        dic["teamName"] = self.teamNameText
        dic["fee"] = self.price
        if self.applyType == 0 {
            let json = NSDictionary(dictionary: self.personlaModel.textDic).toJsonString()
            dic["enrollJson"] = [json]
        }else {
            var jsonArray: [String] = []
            for item in self.teamUserArray {
                if item.textDic.values.first != nil {
                    let content = item.textDic.values.first as? String
                    if content?.isEmpty == false {
                        let json = NSDictionary(dictionary: item.textDic).toJsonString()
                        jsonArray.append(json)
                    }
                }
                
            }
            dic["enrollJson"] = jsonArray
        }
        
        return dic
        
    }
    
    
    // 下单
    func createOrderService()  {
        
        BHCommonService.createOrder(type: 4, businessId: self.businessId, payType: 1) { (success, text) in
            if success == true {
                if text.isEmpty == true {
                    BHToast.toast(text: "生产支付信息失败，请联系客服处理")
                }else {
                    self.orderText = text
                    
                    self.payBottomView.show()
                }
               
            }else {
                BHToast.toast(text: text)
            }
        }
    }
    
    // 去支付
    func goAlipayAct()  {
        BHPayManager.init().begainBuy(orderText: self.orderText) { (success, errorMsg) in
            BHToast.toast(text: errorMsg)
            if success == true {
                
            }
        }
    }
}


extension BHCompetitionApplyViewController {
    func queryGroupService()  {
        let manager = BHHTTPClient.init()
        manager.get(url: String.game_apply_groupInfo_url, paramters: ["eventId":self.gameId]) { (success, errorMsg, responseDic) in
            if success == true {
                let result = BHJsonTool.decodeDicFromDic(dic: responseDic, key: "result")
                
                // 获取条例
                let json = BHJsonTool.decodeStringFromDic(dic: result, key: "enrollJson")
                self.enrollJsonDic = json.transJsonToDic()
                
                if self.applyType == 1 {
                    let model = BHApplyUserModel.init()
                    model.textDic = self.enrollJsonDic
                    self.teamUserArray.append(model)
                }else {
                    self.personlaModel.textDic = self.enrollJsonDic
                }
                
                // 钱
                let price = BHJsonTool.decodeStringFromDic(dic: result, key: "fee")
                self.price = price
                
                // 获取分组
                let team = BHJsonTool.decodeArrayFromDic(dic: result, key: "team")
                if self.groupItemArray.count != 0 {
                    self.groupItemArray.removeAll()
                }
                
                for item in team {
                    if item is NSNull {
                        
                    }else {
                        let model = BHCompetitionApplyGroupItemModel.init()
                        model.parseDic(item as! [String:Any])
                        self.groupItemArray.append(model)
                    }
                }
                if self.groupItemArray.count != 0 {
                    self.choseGroupModel = self.groupItemArray.first!
                    self.choseGroupModel.chose = true
                }
                
                self.tableView.reloadData()
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
    }
}
